#include "wlkOperator.h"


/**
 * @brief 构造函数
 */
WlkOperator::WlkOperator(){

}

/**
 * @brief 析构函数
 */
WlkOperator::~WlkOperator(){

}

Q_INVOKABLE QVariantMap WlkOperator::openWlkFile(bool local){
    QVariantMap result;
    QStringList sFilePath;


    if(local){
        sFilePath.push_back(":/src/data.wlk");
    }else{

        QFileDialog *fDialog=new QFileDialog(NULL,"file dlg","/home","Wlk files(*.wlk)");
        if(fDialog->exec()==QFileDialog::Accepted)
        {
            sFilePath = fDialog->selectedFiles();
        }
    }


    if(sFilePath.length()>0){

        QSqlDatabase db = dbHelper::openConnection();
        QSqlQuery query(db);
        db.transaction();
        QString sql="Delete From AmplProgramTemp ";
        query.exec(sql);
        sql="Delete From AmplStepTemp";
        query.exec(sql);
        sql="Delete From ExperimentInfoTemp";
        query.exec(sql);
        sql="Delete From FluorescenceDataTemp";
        query.exec(sql);
        sql="Delete From SampleInfoTemp";
        query.exec(sql);


        QFile file(sFilePath[0]);
        QTextCodec* codec = QTextCodec::codecForName("GBK");
        file.open(QIODevice::ReadOnly | QIODevice::Text);

        QTextStream txtInput(&file);
        txtInput.setCodec(codec);
        int num=0;
        bool isExpResult=false;
        while (!txtInput.atEnd())
        {
            QString lineStr = txtInput.readLine();

            if(lineStr.contains("FluorescenceDataTemp") && !isExpResult){
                isExpResult = true;
            }
            if(lineStr.contains(".")&&num==0){
                QList<QString> infoList= lineStr.split(',');
                result["EquName"]=infoList[0];
                result["Ip"]=infoList[1];
                result["Port"]=infoList[2];
                result["ExpGuid"]=infoList[3];
                num++;
            }
            else
            {
                query.exec(lineStr);
            }
        }

        db.commit();

        result["FileType"]=isExpResult?"1":"0";
    }else{                          // 用户未选择文件
        result["ExpGuid"] = "";
    }
    return result;
}

Q_INVOKABLE QVariantMap WlkOperator::openWlkFile_getInfo(){
    QVariantMap     res;
    QVariantList    sampleInfo;
    QVariantMap     amplInfo;
    QVariantList    amplStep;
    QVariantMap     expInfo;

    QStringList sFilePath;
    QFileDialog *fDialog=new QFileDialog(NULL,"file dlg","/home","Wlk files(*.wlk)");
    if(fDialog->exec()==QFileDialog::Accepted)
    {
        sFilePath = fDialog->selectedFiles();
    }

    // 读取文件信息到数据库
    if(sFilePath.length()>0){

        res["Res"] = 0;

        QSqlDatabase db = dbHelper::openConnection();
        QSqlQuery query(db);
        QString sql="Delete From SampleInfoOpen";
        query.exec(sql);
        sql = "Delete From AmplProgramOpen";
        query.exec(sql);
        sql = "Delete From AmplStepOpen";
        query.exec(sql);
        sql = "Delete From ExperimentInfoOpen";
        query.exec(sql);


        QFile file(sFilePath[0]);
        QTextCodec* codec = QTextCodec::codecForName("GBK");
        file.open(QIODevice::ReadOnly | QIODevice::Text);

        QTextStream txtInput(&file);
        txtInput.setCodec(codec);
        int num=0;
        while (!txtInput.atEnd())
        {
            QString lineStr = txtInput.readLine();

            // 实验信息读取
            if(lineStr.contains("ExperimentInfoTemp")){
                lineStr.replace("ExperimentInfoTemp", "ExperimentInfoOpen");
                query.exec(lineStr);
            }

            // 扩增程序读取
            if(lineStr.contains("AmplProgramTemp")){
                lineStr.replace("AmplProgramTemp", "AmplProgramOpen");
                query.exec(lineStr);
            }

            // 扩增程序步骤读取
            if(lineStr.contains("AmplStepTemp")){
                lineStr.replace("AmplStepTemp", "AmplStepOpen");
                query.exec(lineStr);
            }

            // 样本信息读取
            if(lineStr.contains("SampleInfoTemp")){
                lineStr.replace("SampleInfoTemp", "SampleInfoOpen");
                query.exec(lineStr);
                num ++;
            }
        }
        if(num == 96){
            res["Res"] = 1;
        }

        db.commit();

    }else{                          // 用户未选择文件
        res["Res"] = 2;
        return res;
    }

    // 从数据库取出信息返回给前端
    if(res["Res"].toInt() != 0){
        QSqlDatabase db = dbHelper::openConnection();
        QSqlQuery query(db);

        // 样本信息
        QString sql=QString("Select ID,ColNum,RowNum,SampleName,SampleType,SampleConc,FAM,ROX,CY5,VIC "
                            "From SampleInfoOpen");
        query.exec(sql);
        while (query.next()) {
            QVariantMap map;
            for (int i = 0; i < query.record().count(); ++i) {
                map[query.record().fieldName(i)] = query.value(i);
            }
            sampleInfo.append(map);
        }

        // 实验信息
        sql = "Select * From ExperimentInfoOpen";
        query.exec(sql);
        while(query.next()){
            for (int i = 0; i < query.record().count(); ++i) {
                expInfo[query.record().fieldName(i)] = query.value(i);
            }
        }

        // 扩增程序信息
        sql = "Select * From AmplProgramOpen";
        query.exec(sql);
        while(query.next()){
            for(int i = 0; i < query.record().count(); i ++){
                amplInfo[query.record().fieldName(i)] = query.value(i);
            }
        }

        // 扩增程序步骤
        sql = "Select * From AmplStep";
        query.exec(sql);
        while(query.next()){
            QVariantMap map;
            for(int i = 0; i < query.record().count(); i ++){
                map[query.record().fieldName(i)] = query.value(i);
            }
            amplStep.append(map);
        }
    }

    res["SampleInfo"] = sampleInfo;
    res["ExpInfo"] = expInfo;
    res["AmplInfo"] = amplInfo;
    res["AmplStep"] = amplStep;
    qDebug() << "getInfo:" << res["ExpInfo"];
    qDebug() << "QDEBUG_SAMPLEINFO" << sampleInfo;
    return res;
}

Q_INVOKABLE QVariantMap WlkOperator::getExperimentInfo(QString expGuid)
{
    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);

    QString  sql=QString("Select AmplName,ExperimentName,Code,"
                         "System,ConsumableType,TestKit "
                         "From ExperimentInfoTemp e "
                         "Where e.Id='%1'").arg(expGuid);

    query.exec(sql);
    QVariantMap map;

    while (query.next()) {
        for (int i = 0; i < query.record().count(); ++i) {

            map[query.record().fieldName(i)] = query.value(i);
        }
    }
    return map;
}

Q_INVOKABLE QVariantList WlkOperator::getSampleInfo(QString expGuid)
{
    QVariantList result;
    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);

    QString  sql=QString("Select ID,ColNum,RowNum,SampleName,SampleType,SampleConc,FAM,ROX,CY5,VIC "
                         "From SampleInfoTemp Where ExperimentGuid='%1'").arg(expGuid);
    query.exec(sql);
    while (query.next()) {
        QVariantMap map;
        for (int i = 0; i < query.record().count(); ++i) {
            map[query.record().fieldName(i)] = query.value(i);
        }
        result.append(map);
    }
    return  result;
}

void WlkOperator::SaveSampleInfo(QString expGuid){
    //数据存储
    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);
    QString firstInfo;

    QString sql=QString("Select EquName,Case when EquConnectType=0 THEN Ip Else SerialPort End as Ip,"
                        "Case when EquConnectType=0 THEN Port Else BaudRate End as Port "
                        "From EquipmentInfo Where id=(Select EquId From ExperimentInfo "
                        "Where id='%1')").arg(expGuid);
    query.exec(sql);
    while (query.next()) {
        firstInfo=query.value("EquName").toString()+","+query.value("Ip").toString()+","+query.value("Port").toString()+","+expGuid;
    }

    //1.实验信息
    QString addSql;
    QString amplGuid;
    sql=QString("Select * from ExperimentInfo where ID='%1'").arg(expGuid);

    query.exec(sql);
    while (query.next()) {
        addSql=QString("Insert into ExperimentInfoTemp values('%1','%2','%3','%4','%5','%6','%7','%8','%9','%10','%11','%12','%13','%14');").arg(query.value("ID").toString(),query.value("EquId").toString(),
                                                                                                                                                 query.value("EquName").toString(),query.value("AmplGuid").toString(),
                                                                                                                                                 query.value("AmplName").toString(),query.value("ExperimentName").toString(),
                                                                                                                                                 query.value("Code").toString(),query.value("System").toString(),
                                                                                                                                                 query.value("ConsumableType").toString(),query.value("TestKit").toString(),
                                                                                                                                                 query.value("WlkSavePath").toString(),query.value("Status").toString(),
                                                                                                                                                 query.value("RunTime").toString(),query.value("FinishTime").toString());
        localPath=query.value("WlkSavePath").toString();
        amplGuid=query.value("AmplGuid").toString();
    }

    QFile file(localPath);
    file.open(QFile::WriteOnly|QFile::Text);

    QTextStream out(&file);  // QTextStream会自动将 Unicode 编码同操作系统的编码进行转换
    QTextCodec* codec = QTextCodec::codecForName("GBK");
    out.setCodec(codec);
    out<<firstInfo+"\n";
    out<<addSql+"\n";

    //1.扩增程序
    if(amplGuid=="0"){
        sql="Select * from AmplProgramOpen";
    }else{
        sql=QString("Select * from AmplProgram "
                    "where "
                    "ID=("
                    "Select AmplGuid from ExperimentInfo where id='%1')").arg(expGuid);
    }


    query.exec(sql);
    while (query.next()) {
        addSql=QString("Insert into AmplProgramTemp values('%1','%2','%3','%4','%5','%6','%7','%8','%9');").arg(query.value("ID").toString(),query.value("IsDefault").toString(),
                                                                                                                query.value("ProgramName").toString(),query.value("Duration").toString(),
                                                                                                                query.value("StepNum").toString(),query.value("HotCoverStatus").toString(),
                                                                                                                query.value("HotCoverTemp").toString(),query.value("CreateDate").toString(),
                                                                                                                query.value("Memo").toString());
    }


    out<<addSql+"\n";

    if(amplGuid=="0"){
        sql="Select * from AmplStepOpen";
    }else{
        sql=QString("Select * from AmplStep "
                    "where "
                    "programId=("
                    "Select AmplGuid from ExperimentInfo where id='%1') order by StepNum").arg(expGuid);
    }

    query.exec(sql);
    while (query.next()) {
        addSql=QString("Insert into AmplStepTemp values('%1','%2','%3','%4','%5','%6','%7','%8','%9');").arg(query.value("ID").toString(),query.value("ProgramId").toString(),
                                                                                                             query.value("StepNum").toString(),query.value("Temperature").toString(),
                                                                                                             query.value("ExecutionTime").toString(),query.value("Rate").toString(),
                                                                                                             query.value("IsCollect").toString(),query.value("CycleNumber").toString(),
                                                                                                             query.value("CycleNum").toString());
        out<<addSql+"\n";
    }

    sql=QString("Select * from SampleInfo Where ExperimentGuid='%1'").arg(expGuid);
    query.exec(sql);
    while (query.next()) {
        addSql=QString("Insert into SampleInfoTemp values('%1','%2','%3','%4','%5','%6','%7','%8','%9','%10','%11','%12');").arg(query.value("ID").toString(),query.value("ExperimentGuid").toString(),
                                                                                                                                 query.value("ColNum").toString(),query.value("RowNum").toString(),
                                                                                                                                 query.value("SampleName").toString(),query.value("SampleType").toString(),
                                                                                                                                 query.value("SampleConc").toString(),query.value("Pos").toString(),
                                                                                                                                 query.value("FAM").toString(),query.value("ROX").toString(),
                                                                                                                                 query.value("CY5").toString(),query.value("VIC").toString());
        out<<addSql+"\n";
    }

    file.close();
}

void WlkOperator::SaveResultInfo(QString equGuid){

    QString autosaveName;

    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);
    QString firstInfo;

    QString expGuid;
    QString sql=QString("Select ExperimentGuid From EquipmentInfo Where id='%1'").arg(equGuid);
    query.exec(sql);
    while (query.next()) {
        expGuid=query.value("ExperimentGuid").toString();
    }

    sql=QString("Select EquName,Case when EquConnectType=0 THEN Ip Else SerialPort End as Ip,"
                "Case when EquConnectType=0 THEN Port Else BaudRate End as Port "
                "From EquipmentInfo Where id=(Select EquId From ExperimentInfo "
                "Where id='%1')").arg(expGuid);
    query.exec(sql);
    while (query.next()) {
        firstInfo=query.value("EquName").toString()+","+query.value("Ip").toString()+","+query.value("Port").toString()+","+expGuid;
    }

    //1.实验信息
    QString addSql;

    sql=QString("Select * from ExperimentInfo where ID='%1'").arg(expGuid);

    query.exec(sql);
    QString amplGuid;
    while (query.next()) {
        addSql=QString("Insert into ExperimentInfoTemp values('%1','%2','%3','%4','%5','%6','%7','%8','%9','%10','%11','%12','%13','%14');").arg(query.value("ID").toString(),query.value("EquId").toString(),
                                                                                                                                                 query.value("EquName").toString(),query.value("AmplGuid").toString(),
                                                                                                                                                 query.value("AmplName").toString(),query.value("ExperimentName").toString(),
                                                                                                                                                 query.value("Code").toString(),query.value("System").toString(),
                                                                                                                                                 query.value("ConsumableType").toString(),query.value("TestKit").toString(),
                                                                                                                                                 query.value("WlkSavePath").toString(),query.value("Status").toString(),
                                                                                                                                                 query.value("RunTime").toString(),query.value("FinishTime").toString());
        localPath=query.value("WlkSavePath").toString();
        autosaveName = query.value("RunTime").toString().remove(":").remove(" ").remove("-");
        amplGuid=query.value("AmplGuid").toString();
    }

    QFile file(localPath);
    file.open(QFile::WriteOnly|QFile::Text);

    QTextStream out(&file);  // QTextStream会自动将 Unicode 编码同操作系统的编码进行转换
    QTextCodec* codec = QTextCodec::codecForName("GBK");
    out.setCodec(codec);
    out<<firstInfo+"\n";
    out<<addSql+"\n";

    //1.扩增程序
    if(amplGuid=="0"){
        sql="Select * from AmplProgramOpen";
    }else{
        sql=QString("Select * from AmplProgram "
                    "where "
                    "ID=("
                    "Select AmplGuid from ExperimentInfo where id='%1')").arg(expGuid);
    }
    query.exec(sql);
    while (query.next()) {
        addSql=QString("Insert into AmplProgramTemp values('%1','%2','%3','%4','%5','%6','%7','%8','%9');").arg(query.value("ID").toString(),query.value("IsDefault").toString(),
                                                                                                                query.value("ProgramName").toString(),query.value("Duration").toString(),
                                                                                                                query.value("StepNum").toString(),query.value("HotCoverStatus").toString(),
                                                                                                                query.value("HotCoverTemp").toString(),query.value("CreateDate").toString(),
                                                                                                                query.value("Memo").toString());
    }


    out<<addSql+"\n";
    if(amplGuid=="0"){
        sql="Select * from AmplStepOpen";
    }else{
        sql=QString("Select * from AmplStep "
                    "where "
                    "programId=("
                    "Select AmplGuid from ExperimentInfo where id='%1') order by StepNum").arg(expGuid);
    }
    query.exec(sql);
    while (query.next()) {
        addSql=QString("Insert into AmplStepTemp values('%1','%2','%3','%4','%5','%6','%7','%8','%9');").arg(query.value("ID").toString(),query.value("ProgramId").toString(),
                                                                                                             query.value("StepNum").toString(),query.value("Temperature").toString(),
                                                                                                             query.value("ExecutionTime").toString(),query.value("Rate").toString(),
                                                                                                             query.value("IsCollect").toString(),query.value("CycleNumber").toString(),
                                                                                                             query.value("CycleNum").toString());
        out<<addSql+"\n";
    }

    sql=QString("Select * from SampleInfo Where ExperimentGuid='%1'").arg(expGuid);
    query.exec(sql);
    while (query.next()) {
        addSql=QString("Insert into SampleInfoTemp values('%1','%2','%3','%4','%5','%6','%7','%8','%9','%10','%11','%12');").arg(query.value("ID").toString(),query.value("ExperimentGuid").toString(),
                                                                                                                                 query.value("ColNum").toString(),query.value("RowNum").toString(),
                                                                                                                                 query.value("SampleName").toString(),query.value("SampleType").toString(),
                                                                                                                                 query.value("SampleConc").toString(),query.value("Pos").toString(),
                                                                                                                                 query.value("FAM").toString(),query.value("ROX").toString(),
                                                                                                                                 query.value("CY5").toString(),query.value("VIC").toString());
        out<<addSql+"\n";
    }

    sql=QString("Select * from FluorescenceData Where ExperimentGuid='%1'").arg(expGuid);
    query.exec(sql);
    while (query.next()) {
        addSql=QString("Insert into FluorescenceDataTemp values('%1','%2','%3','%4','%5','%6','%7','%8','%9');").arg(query.value("ID").toString(),query.value("ExperimentGuid").toString(),query.value("SampleId").toString(),
                                                                                                                     query.value("PositionNumber").toString(),query.value("CyclesNumber").toString(),
                                                                                                                     query.value("FAM").toString(),query.value("ROX").toString(),
                                                                                                                     query.value("CY5").toString(),query.value("VIC").toString());
        out<<addSql+"\n";
    }
    file.close();

    // wlk文件默认存储
    QDir dir;
    if (!(dir.exists("wlk")))
        dir.mkpath("wlk");

    QFile::copy(localPath, "wlk/"+autosaveName);

}

